import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { login, getUserInfo, logout } from '@/apis/auth'

const KEY_TOKEN = 'token'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(KEY_TOKEN) || '',
    showAdminOpts: false,
    userInfo: {
      id: '',
      avatar: '',
      accountType: 666,
      account: '',
      name: '',
      age: 0,
      email: ''
    }
  }),
  getters: {
    userName: (state) => state.userInfo.name,
    userAge: (state) => state.userInfo.age,
    userEmail: (state) => state.userInfo.email
  },
  actions: {
    setToken(token: string) {
      this.token = token

      // console.log('setToken', token)
      localStorage.setItem(KEY_TOKEN, token)
    },
    fetchUserInfo() {
      if (!this.token) {
        console.log('Token is not set')
        return
      }
      getUserInfo().then((response) => {
        const { code, message, result } = response.data
        if (code === 200) {
          this.userInfo = result
        } else {
          this.setToken('')
          console.error(message)
        }
      })
    },
    loginAccount(data: Object) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((response) => {
            const { code, message, result } = response.data
            this.setToken(result.accessToken)
            // console.log(result.accessToken)
            // this.setUserInfo(result)
            this.fetchUserInfo()
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    loginOut() {
      logout().then((response) => {
        const { code, message } = response.data
        if (code === 200) {
          this.setToken('')
          this.userInfo = {
            avatar: '',
            accountType: 666,
            id: '',
            account: '',
            name: '',
            age: 0,
            email: ''
          }
          localStorage.removeItem(KEY_TOKEN)
        } else {
          console.error(message)
        }
      })
    }
  }
})
